package com.shengsiyuan.netty.thirdexample.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class MyChatServerHandler extends SimpleChannelInboundHandler<String> {

    /**
     * GlobalEventExecutor是单线程单实例，会自动启动线程，并且在任务队列中没有任务时1秒钟后停止。
     */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();

        channelGroup.forEach(ch -> {
            System.out.println(channel.remoteAddress() + "发消息：" + msg + "\n");
            if (ch != channel) {
                ch.writeAndFlush(channel.remoteAddress() + "发消息：" + msg + "\n");
            } else {
                ch.writeAndFlush("[自己]:" + msg + "\n");
            }
        });
    }

    /**
     * 客户端与服务端建立连接时回调
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        // 进行广播（底层会遍历group中的每个channel.writeAndFlush()方法）
        channelGroup.writeAndFlush("[客服端]" + channel.remoteAddress() + "加入\n");

        channelGroup.add(channel);
    }

    /**
     * 连接处于活动状态时回调
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(ctx.channel().remoteAddress() + "上线了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(ctx.channel().remoteAddress() + "下线");
    }

    /**
     * 客户端与服务端断开连接时回调。
     * 如果像手机打开飞行模式或强制关机，这时服务端是不会回调这个方法的。
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();

        channelGroup.writeAndFlush("[客服端]" + channel.remoteAddress() + "离开\n");
        System.out.println(channelGroup.size());

        // 连接断了后，netty会自动把channelGroup中断掉的通道移除
        //channelGroup.remove(channel);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
